package com.sunxd.vue.infrastructure.adapter.db.repository;

import com.sunxd.vue.domain.bean.domain.User;
import com.sunxd.vue.domain.repository.UserRepository;
import com.sunxd.vue.infrastructure.adapter.db.base.Paging;
import com.sunxd.vue.infrastructure.adapter.db.mapping.UserMapping;
import com.sunxd.vue.infrastructure.adapter.db.dao.UserDao;
import com.sunxd.vue.infrastructure.adapter.db.po.UserPO;
import com.sunxd.vue.infrastructure.utils.PagingUtil;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;

@Component
@AllArgsConstructor
public class UserRepositoryImpl implements UserRepository {

    private final UserDao userDao;

    @Override
    public boolean save(User user) {
        return userDao.create(UserMapping.CONVERTER.domain2po(user));
    }

    @Override
    public boolean update(User user) {
        return userDao.update(UserMapping.CONVERTER.domain2po(user));
    }

    @Override
    public Paging<User> paging(Map<String, Object> param) {
        return PagingUtil.toPaging(userDao.paging(param), UserMapping.CONVERTER::po2domain);
    }

    @Override
    public User findByName(String name) {
        UserPO userPO = new UserPO();
        userPO.setName(name);
        List<UserPO> list = userDao.list(userPO);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return UserMapping.CONVERTER.po2domain(list.get(0));
    }

    @Override
    public User findOne(User user) {
        List<UserPO> list = userDao.list(UserMapping.CONVERTER.domain2po(user));
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        return UserMapping.CONVERTER.po2domain(list.get(0));
    }
}
